package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"src/models/mysql"
	"src/pkg"
	"strconv"

	"src/internal/svc"
	"src/src"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderGoodLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderGoodLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderGoodLogic {
	return &OrderGoodLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderGoodLogic) OrderGood(in *src.OrderGoodRequest) (*src.OrderGoodResponse, error) {
	// todo: add your logic here and delete this line

	var good mysql.Good
	err := good.GoodFind(int(in.Id))

	if err != nil {
		return nil, fmt.Errorf("商品不存在")
	}

	if good.Stock < int(in.Stock) {
		return nil, fmt.Errorf("库存不足")
	}

	Total := good.Price * int(in.Stock)
	NumberIng := uuid.NewString()

	o := mysql.Order{
		Model:     gorm.Model{},
		Total:     Total,
		NumberIng: NumberIng,
		Title:     good.Title,
		Stock:     good.Stock,
		Status:    good.Status,
	}
	err = o.Order()
	if err != nil {
		return nil, fmt.Errorf("订单生成失败")
	}

	og := mysql.OrderGood{
		Model:     gorm.Model{},
		Total:     Total,
		NumberIng: NumberIng,
		Price:     good.Price,
		Stock:     good.Stock,
		Status:    good.Status,
	}
	err = og.OrderGood()
	if err != nil {
		return nil, fmt.Errorf("订单生成失败")
	}

	Group := pkg.Group{
		Subject:     good.Title,
		OutTradeNo:  NumberIng,
		TotalAmount: strconv.Itoa(Total),
	}
	url := Group.Alipay()

	return &src.OrderGoodResponse{
		Url:     url,
		OrderId: int64(good.ID),
	}, nil
}
